{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "# Literal\n",
    "Literal 是 Python 的类型注解工具之一，用于指定变量或参数只能接受特定的字面值。Literal 可以帮助提高代码的可读性和类型安全性，尤其是在需要限制变量值的情况下。Literal 是在 Python 3.8 中引入的，并且在 typing 模块中可用。\n",
    "## 基本用法"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "cd093e2559ae4bf6"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Setting status to: active\n",
      "Setting status to: unknown\n"
     ]
    }
   ],
   "source": [
    "from typing import Literal\n",
    "\n",
    "\n",
    "def set_status(status: Literal['active', 'inactive']) -> None:\n",
    "    print(f\"Setting status to: {status}\")\n",
    "\n",
    "\n",
    "set_status('active')  # 正确\n",
    "set_status('unknown')  # 错误，会引发类型检查器警告\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-11-01T07:41:57.538769Z",
     "start_time": "2024-11-01T07:41:57.531631Z"
    }
   },
   "id": "dc2739982d3fd7a8",
   "execution_count": 1
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 多个字面值"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "416696d47828b625"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Setting mode to: read\n",
      "Setting mode to: execute\n"
     ]
    }
   ],
   "source": [
    "from typing import Literal\n",
    "\n",
    "\n",
    "def set_mode(mode: Literal['read', 'write', 'append']) -> None:\n",
    "    print(f\"Setting mode to: {mode}\")\n",
    "\n",
    "\n",
    "set_mode('read')  # 正确\n",
    "set_mode('execute')  # 错误，会引发类型检查器警告\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-11-01T07:42:37.156805Z",
     "start_time": "2024-11-01T07:42:37.149332Z"
    }
   },
   "id": "b3d1332dd5485d3e",
   "execution_count": 2
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 结合其他类型注解"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "68ef6e9bb34bacf3"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Configuring with option: debug and level: low\n",
      "Configuring with option: release and level: 5\n",
      "Configuring with option: debug and level: medium\n"
     ]
    }
   ],
   "source": [
    "from typing import Literal, Union\n",
    "\n",
    "\n",
    "def configure(option: Literal['debug', 'release'], level: Union[Literal['low', 'high'], int]) -> None:\n",
    "    print(f\"Configuring with option: {option} and level: {level}\")\n",
    "\n",
    "\n",
    "configure('debug', 'low')  # 正确\n",
    "configure('release', 5)  # 正确\n",
    "configure('debug', 'medium')  # 错误，会引发类型检查器警告\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-11-01T07:43:24.273708Z",
     "start_time": "2024-11-01T07:43:24.267527Z"
    }
   },
   "id": "30dad78b60ee3add",
   "execution_count": 3
  },
  {
   "cell_type": "markdown",
   "source": [
    "# Union\n",
    "Union 是 Python 的类型注解工具之一，用于表示一个变量或参数可以接受多种类型中的任意一种。Union 允许你在类型注解中指定多个可能的类型，从而提高代码的灵活性和类型安全性。Union 是在 typing 模块中提供的。\n",
    "## 基本用法"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "ad85af6fee36f1f5"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "can only concatenate str (not \"int\") to str",
     "output_type": "error",
     "traceback": [
      "\u001B[0;31m---------------------------------------------------------------------------\u001B[0m",
      "\u001B[0;31mTypeError\u001B[0m                                 Traceback (most recent call last)",
      "Cell \u001B[0;32mIn[4], line 9\u001B[0m\n\u001B[1;32m      7\u001B[0m result2 \u001B[38;5;241m=\u001B[39m add(\u001B[38;5;241m1.5\u001B[39m, \u001B[38;5;241m2.5\u001B[39m)  \u001B[38;5;66;03m# 正确\u001B[39;00m\n\u001B[1;32m      8\u001B[0m result3 \u001B[38;5;241m=\u001B[39m add(\u001B[38;5;241m1\u001B[39m, \u001B[38;5;241m2.5\u001B[39m)  \u001B[38;5;66;03m# 正确\u001B[39;00m\n\u001B[0;32m----> 9\u001B[0m result4 \u001B[38;5;241m=\u001B[39m add(\u001B[38;5;124m\"\u001B[39m\u001B[38;5;124m1\u001B[39m\u001B[38;5;124m\"\u001B[39m, \u001B[38;5;241m2\u001B[39m)\n",
      "Cell \u001B[0;32mIn[4], line 4\u001B[0m, in \u001B[0;36madd\u001B[0;34m(a, b)\u001B[0m\n\u001B[1;32m      3\u001B[0m \u001B[38;5;28;01mdef\u001B[39;00m \u001B[38;5;21madd\u001B[39m(a: Union[\u001B[38;5;28mint\u001B[39m, \u001B[38;5;28mfloat\u001B[39m], b: Union[\u001B[38;5;28mint\u001B[39m, \u001B[38;5;28mfloat\u001B[39m]) \u001B[38;5;241m-\u001B[39m\u001B[38;5;241m>\u001B[39m Union[\u001B[38;5;28mint\u001B[39m, \u001B[38;5;28mfloat\u001B[39m]:\n\u001B[0;32m----> 4\u001B[0m     \u001B[38;5;28;01mreturn\u001B[39;00m a \u001B[38;5;241m+\u001B[39m b\n",
      "\u001B[0;31mTypeError\u001B[0m: can only concatenate str (not \"int\") to str"
     ]
    }
   ],
   "source": [
    "from typing import Union\n",
    "\n",
    "\n",
    "def add(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:\n",
    "    return a + b\n",
    "\n",
    "\n",
    "result1 = add(1, 2)  # 正确\n",
    "result2 = add(1.5, 2.5)  # 正确\n",
    "result3 = add(1, 2.5)  # 正确\n",
    "result4 = add(\"1\", 2)  # 错误，会引发类型检查器警告\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-11-01T07:45:04.971606Z",
     "start_time": "2024-11-01T07:45:04.491090Z"
    }
   },
   "id": "4701bb90e3753646",
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "source": [
    "# Callable\n",
    "Callable 是一个类型提示，用于表示可调用对象。它通常用于函数签名中，以指示某个参数或返回值是一个函数或其他可调用对象。基本用法：\n",
    "- **Callable[[ArgType1, ArgType2, ...], ReturnType]**  表示一个接受特定参数类型并返回特定类型的可调用对象。\n",
    "例如，Callable[[int, str], float] 表示一个接受一个整数和一个字符串作为参数，并返回一个浮点数的函数。\n",
    "- 如果函数接受可变数量的参数，可以使用 *args 和 **kwargs。\n",
    "例如，Callable[..., ReturnType] 表示一个接受任意参数并返回特定类型的函数\n",
    "\n",
    "## 基本用法"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "dffe830bc60a3cea"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "7\n"
     ]
    }
   ],
   "source": [
    "from typing import Callable\n",
    "\n",
    "\n",
    "def add(a: int, b: int) -> int:\n",
    "    return a + b\n",
    "\n",
    "\n",
    "def apply(func: Callable[[int, int], int], x: int, y: int) -> int:\n",
    "    return func(x, y)\n",
    "\n",
    "\n",
    "result = apply(add, 3, 4)\n",
    "print(result)  # 输出 7\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-11-04T05:33:56.100692Z",
     "start_time": "2024-11-04T05:33:56.093827Z"
    }
   },
   "id": "1c9a8a0610998eb2",
   "execution_count": 6
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 可变参数\n"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "281d31f150f5fbf1"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "from typing import Callable\n",
    "\n",
    "\n",
    "def sum_all(*args: int) -> int:\n",
    "    return sum(args)\n",
    "\n",
    "\n",
    "def apply_variadic(func: Callable[..., int], *args: int) -> int:\n",
    "    return func(*args)\n",
    "\n",
    "\n",
    "result = apply_variadic(sum_all, 1, 2, 3, 4)\n",
    "print(result)  # 输出 10\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-11-04T05:34:51.747568Z",
     "start_time": "2024-11-04T05:34:51.741932Z"
    }
   },
   "id": "ca9947996940e551",
   "execution_count": 7
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 无返回值"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "f3832e1622ba88ea"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Alice!\n"
     ]
    }
   ],
   "source": [
    "from typing import Callable\n",
    "\n",
    "\n",
    "def greet(name: str) -> None:\n",
    "    print(f\"Hello, {name}!\")\n",
    "\n",
    "\n",
    "def apply_no_return(func: Callable[[str], None], name: str) -> None:\n",
    "    func(name)\n",
    "\n",
    "\n",
    "apply_no_return(greet, \"Alice\")\n",
    "  "
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-11-04T05:36:12.470644Z",
     "start_time": "2024-11-04T05:36:12.465168Z"
    }
   },
   "id": "c13b3963ccc6364e",
   "execution_count": 8
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
